package com.gs.synedocket.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.gs.synedocket.constant.SyncStatus;
import com.gs.synedocket.db.dao.LogUtil;
import com.gs.synedocket.db.sqlite.DBApi;
import com.gs.synedocket.util.DateUtil;
import com.gs.synedocket.util.SyncDownloadUtil;
import com.gs.synedocket.util.SyncUploadUtil;

import java.util.Date;

public class ClearOldDataService extends Service {

    private static final String TAG = "ClearData";
    private static final String DO_TIME = "12:00";
    private static final long SLEEP_TIME = 60000L;
    private static boolean loop = true;
    private static Thread mThread;
    private boolean isDelete;

    public static void stopThread() {
        loop = false;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        loop = true;
        if (mThread == null) {
            mThread = new Thread(() -> {
                while (loop) {
                    try {
                        Thread.sleep(SLEEP_TIME);
                    } catch (InterruptedException ignored) {

                    }
                    clearOldData();
                }
            });
            mThread.start();
        }
        return START_STICKY;
    }

    private void clearOldData() {
        try {
            String nowTime = DateUtil.DateTimeToStr(new Date(), "HH:mm");
            Log.i(TAG, "clearOldData: currentTime:" + nowTime);
            Log.i(TAG, "clearOldData: DO_TIME:" + DO_TIME);
            // 每天12点删除3个月前的数据
//        if (isDelete ||SyncUploadUtil.getInstance().isUpload() ||SyncDownloadUtil.getInstance().isDownload()) { // 测试用
            if (!nowTime.equals(DO_TIME) || isDelete || SyncStatus.isSync()) {
//            if (!nowTime.equals(DO_TIME) || isDelete || SyncUploadUtil.getInstance().isUpload() || SyncDownloadUtil.getInstance().isDownload()) {
                return;
            }
            isDelete = true;
            String date = DateUtil.getFrontDate(new Date(), 90);
            Log.i(TAG, "clearOldData: 开始删除数据" + 90 + "天前的日期：" + date);
            DBApi.getInstance().deleteOldData(date);
        } catch (Exception e) {
            LogUtil.getInstance().insertOrReplaceData("删除3个月前的数据失败：" + e);
        } finally {
            isDelete = false;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
